/** @type {import('@grapecity/spread-sheets')} */
var GC = window.GC;

function _getElementById(id) {
    return document.getElementById(id);
}

function _getElementByClass(className) {
    return document.getElementsByClassName(className);
}

window.onload = function () {
    var oldEvent = EventTarget.prototype.addEventListener
    EventTarget.prototype.addEventListener = function (type, _fn, opt) {
        // console.log('addEventListener',...args)
        var fn = _fn;
        if (type === 'mousewheel') {
            fn = function (ev) {
                // 感觉有时候生效，有时候不生效
                if (ev.currentTarget.id.indexOf('vp_vp') > -1) {
                    if (ev.altKey || ev.shiftKey) {
                        // TODO: 不加这段，水平滚动时感觉有卡顿，而且有时候不生效
                        // window.spread.options.scrollByPixel = true
                        var scrollDelta = ev.wheelDelta
                        window.spread.getActiveSheet().scroll(0, -scrollDelta)
                        return
                    }
                }
                _fn(ev);
            }
        }
        oldEvent.call(this, type, fn, opt)
    }

    var spread = new GC.Spread.Sheets.Workbook(document.getElementById("ss"), { sheetCount: 6 });
    spread.fromJSON()
    initSpread(spread);

    _getElementById("btnSetPrintInfo").addEventListener("click", setPrintInfo);

    _getElementById("btnPrint").addEventListener("click", function () {
        spread.print(0);
    });

    _getElementById("waterMarkAdd").addEventListener("click", addWaterMark);

    _getElementById("waterMarkClear").addEventListener("click", function () {
        var listDiv = _getElementById("waterMarkList");
        listDiv.innerHTML = "";
        listDiv.waterMarkList = [];
    });

    _getElementById("displayPrintLine").addEventListener("click", function () {
        var sheet = spread.getActiveSheet();
        sheet.isPrintLineVisible(_getElementById("displayPrintLine").checked);
    });
    _getElementById("selectTypeHeaderFooter").addEventListener("change", function (e) {
        var type = parseInt(e.target.value);
        var types = _getElementByClass("headfooter");
        var diffFirst = _getElementByClass("differentFirstPage").item(0);
        var diffOddEven = _getElementByClass("differentOddAndEvenPages").item(0);
        if (type === 1) {
            diffFirst.className = diffFirst.className.replace(/hidden/g, "");
        } else {
            diffFirst.className += " hidden";
        }
        if (type === 2 || type === 3) {
            diffOddEven.className = diffOddEven.className.replace(/hidden/g, "");
        } else {
            diffOddEven.className += " hidden";
        }
        for (let index = 0; index < types.length; index++) {
            const node = types[index];
            if (node.className.indexOf("hidden") == -1) {
                node.className += " hidden";
            }
            if (node.children.item(1).className.indexOf("hidden") == -1) {
                node.children.item(1).className += " hidden";
            }
            if (type === index) {
                node.className = node.className.replace(/hidden/g, "");
            }
        }
    });

    var titles = _getElementByClass("title");
    for (var i = 0; i < titles.length; i++) {
        titles[i].addEventListener("click", toggleClass);
    }
};

/** @param {import('@grapecity/spread-sheets').Spread.Sheets.Workbook} spread */
function initSpread(spread) {
    var sd = data;
    if (sd && sd.sheets) {
        if (!spread) {
            return;
        }
        spread.suspendPaint();

        // spread.fromJSON(sd);
        spread.fromJSON(jsonData11);
        var sheet = spread.sheets[0];
        adjustLayoutForPrint(sheet);
        sheet.options.gridline.showVerticalGridline = true;
        sheet.options.gridline.showHorizontalGridline = false;
        initPrintInfo(sheet);
        window.spread = spread;
        spread.resumePaint();
    }
}

/** @param {import('@grapecity/spread-sheets').Spread.Sheets.Worksheet} sheet */
function setBindPath(sheet) {
    var sheet = spread.getActiveSheet();
    var json = sheet.toJSON();
    var cells = json.data.dataTable;
    Object.keys(cells).map(row => {
        Object.keys(cells[row]).map(col => {
            var cell = cells[row][col] || {}
            var val = (cell.value + '') || ''
            if (val.indexOf('{') > -1 && val.indexOf('}') > -1) {
                var path = cell.value.match(/\{\s*?([^\s]*)\s*?\}/)[1]
                sheet.setBindingPath(row, col, path)
            }
        })
    })
}
function setDataSource(data) {
    var sheet = spread.getActiveSheet();
    sheet.setDataSource(new GC.Spread.Sheets.Bindings.CellBindingSource(data));
}

/**
 * @param {import('@grapecity/spread-sheets').Spread.Sheets.Worksheet} sheet
 */
function initPrintInfo(sheet) {
    /** @type {import('@grapecity/spread-sheets').Spread.Sheets.Print.PrintInfo} */
    var printInfo = sheet.printInfo();
    // custom printInfo for default output
    printInfo.showBorder(false);
    printInfo.showGridLine(false);

    printInfo.rowStart(0);
    printInfo.rowEnd(45);
    printInfo.columnStart(0);
    printInfo.columnEnd(-1);
    printInfo.repeatRowStart(0);
    printInfo.repeatRowEnd(0);
    sheet.setColumnPageBreak(2, true); // 指定打印，从第二列前插入分割符

    printInfo.showColumnHeader(GC.Spread.Sheets.Print.PrintVisibilityType.hide);
    printInfo.showRowHeader(GC.Spread.Sheets.Print.PrintVisibilityType.hide);

    sheet.isPrintLineVisible(true);
    printInfo.orientation(GC.Spread.Sheets.Print.PrintPageOrientation.landscape);
    printInfo.pageOrder(GC.Spread.Sheets.Print.PrintPageOrder.overThenDown);
    printInfo.paperSize(new GC.Spread.Sheets.Print.PaperSize(GC.Spread.Sheets.Print.PaperKind.a4));

    printInfo.pageHeaderFooter({
        normal: {
            header: {
                left: "&G",
                center: "Olympic Athletes",
                // leftImage: "$DEMOROOT$/spread/source/images/olympic.jpg",
            },
            footer: {
                center: "&P/&N",
            },
        },
    });

    // sync with UI setting items
    _getElementById("showBorder").checked = printInfo.showBorder();
    _getElementById("showGridLine").checked = printInfo.showGridLine();
    _getElementById("columnStart").value = printInfo.columnStart();
    _getElementById("columnEnd").value = printInfo.columnEnd();
    _getElementById("rowStart").value = printInfo.rowStart();
    _getElementById("rowEnd").value = printInfo.rowEnd();
    _getElementById("repeatRowStart").value = printInfo.repeatRowStart();
    _getElementById("repeatRowEnd").value = printInfo.repeatRowEnd();

    _getElementById("repeatColumnStart").value = printInfo.repeatColumnStart();
    _getElementById("repeatColumnEnd").value = printInfo.repeatColumnEnd();
    _getElementById("displayPrintLine").checked = sheet.isPrintLineVisible();
    _getElementById("showRowHeader").value = printInfo.showRowHeader();
    _getElementById("orientation").value = printInfo.orientation();
    _getElementById("pageOrder").value = printInfo.pageOrder();
    _getElementById("showColumnHeader").value = printInfo.showColumnHeader();
    var headerFooter = printInfo.pageHeaderFooter();
    var normal = headerFooter.normal;
    _getElementById("headerLeft").value = normal.header.left;
    _getElementById("headerLeftImage").selected = normal.header.leftImage;
    _getElementById("headerCenter").value = normal.header.center;
    _getElementById("headerCenterImage").selected = normal.header.centerImage;
    _getElementById("headerRight").value = normal.header.right || "";
    _getElementById("headerRightImage").selected = normal.header.rightImage;
    _getElementById("footerLeft").value = normal.footer.left || "";
    _getElementById("footerLeftImage").selected = normal.footer.leftImage;
    _getElementById("footerCenter").value = normal.footer.center;
    _getElementById("footerCenterImage").selected = normal.footer.centerImage;
    _getElementById("footerRight").value = normal.footer.right || "";
    _getElementById("footerRightImage").selected = normal.footer.rightImage;
}

function setPrintInfo() {
    function setPrintInfoNumberValueItem(printInfo, key, method) {
        var value = parseInt(_getElementById(key).value),
            method = method || key;
        if (!isNaN(value)) {
            printInfo[method](value);
        }
    }

    var spread = GC.Spread.Sheets.findControl("ss");
    var sheet = spread.getActiveSheet(),
        printInfo = sheet.printInfo();
    sheet.suspendPaint();

    ["rowStart", "rowEnd", "columnStart", "columnEnd", "repeatRowStart", "repeatRowEnd", "repeatColumnStart", "repeatColumnEnd"].forEach(function (name) {
        setPrintInfoNumberValueItem(printInfo, name);
    });

    printInfo.showBorder(_getElementById("showBorder").checked);
    printInfo.showGridLine(_getElementById("showGridLine").checked);
    printInfo.showRowHeader(parseInt(_getElementById("showRowHeader").value));
    printInfo.orientation(parseInt(_getElementById("orientation").value));
    printInfo.pageOrder(parseInt(_getElementById("pageOrder").value));
    printInfo.showColumnHeader(parseInt(_getElementById("showColumnHeader").value));
    printInfo.pageHeaderFooter({
        normal: {
            header: {
                left: _getElementById("headerLeft").value,
                leftImage: _getElementById("headerLeftImage").value,
                center: _getElementById("headerCenter").value,
                centerImage: _getElementById("headerCenterImage").value,
                right: _getElementById("headerRight").value,
                rightImage: _getElementById("headerRightImage").value,
            },
            footer: {
                left: _getElementById("footerLeft").value,
                leftImage: _getElementById("footerLeftImage").value,
                center: _getElementById("footerCenter").value,
                centerImage: _getElementById("footerCenterImage").value,
                right: _getElementById("footerRight").value,
                rightImage: _getElementById("footerRightImage").value,
            },
        },
        first: {
            header: {
                left: _getElementById("headerLeftOfFirstPage").value,
                leftImage: _getElementById("headerLeftImageOfFirstPage").value,
                center: _getElementById("headerCenterOfFirstPage").value,
                centerImage: _getElementById("headerCenterImageOfFirstPage").value,
                right: _getElementById("headerRightOfFirstPage").value,
                rightImage: _getElementById("headerRightImageOfFirstPage").value,
            },
            footer: {
                left: _getElementById("footerLeftOfFirstPage").value,
                leftImage: _getElementById("footerLeftImageOfFirstPage").value,
                center: _getElementById("footerCenterOfFirstPage").value,
                centerImage: _getElementById("footerCenterImageOfFirstPage").value,
                right: _getElementById("footerRightOfFirstPage").value,
                rightImage: _getElementById("footerRightImageOfFirstPage").value,
            },
        },
        odd: {
            header: {
                left: _getElementById("headerLeftOfOddPages").value,
                leftImage: _getElementById("headerLeftImageOfOddPages").value,
                center: _getElementById("headerCenterOfOddPages").value,
                centerImage: _getElementById("headerCenterImageOfOddPages").value,
                right: _getElementById("headerRightOfOddPages").value,
                rightImage: _getElementById("headerRightImageOfOddPages").value,
            },
            footer: {
                left: _getElementById("footerLeftOfOddPages").value,
                leftImage: _getElementById("footerLeftImageOfOddPages").value,
                center: _getElementById("footerCenterOfOddPages").value,
                centerImage: _getElementById("footerCenterImageOfOddPages").value,
                right: _getElementById("footerRightOfOddPages").value,
                rightImage: _getElementById("footerRightImageOfOddPages").value,
            },
        },
        even: {
            header: {
                left: _getElementById("headerLeftOfEvenPages").value,
                leftImage: _getElementById("headerLeftImageOfEvenPages").value,
                center: _getElementById("headerCenterOfEvenPages").value,
                centerImage: _getElementById("headerCenterImageOfEvenPages").value,
                right: _getElementById("headerRightOfEvenPages").value,
                rightImage: _getElementById("headerRightImageOfEvenPages").value,
            },
            footer: {
                left: _getElementById("footerLeftOfEvenPages").value,
                leftImage: _getElementById("footerLeftImageOfEvenPages").value,
                center: _getElementById("footerCenterOfEvenPages").value,
                centerImage: _getElementById("footerCenterImageOfEvenPages").value,
                right: _getElementById("footerRightOfEvenPages").value,
                rightImage: _getElementById("footerRightImageOfEvenPages").value,
            },
        },
    });
    printInfo.differentFirstPage(_getElementById("differentFirstPage").checked);
    printInfo.differentOddAndEvenPages(_getElementById("differentOddAndEvenPages").checked);

    printInfo.watermark(_getElementById("waterMarkList").waterMarkList);
    sheet.resumePaint();
}

function addWaterMark() {
    var watermark = {};
    watermark.x = _getElementById("waterMarkX").value;
    watermark.y = _getElementById("waterMarkY").value;
    watermark.width = _getElementById("waterMarkWidth").value;
    watermark.height = _getElementById("waterMarkHeight").value;
    watermark.imageSrc = _getElementById("waterMarkImage").value;
    watermark.page = _getElementById("waterMarkPage").value;

    var node = document.createElement("option");
    node.innerText = JSON.stringify(Object.values(watermark));
    var listDiv = _getElementById("waterMarkList");
    listDiv.appendChild(node);
    if (!listDiv.waterMarkList) {
        listDiv.waterMarkList = [];
    }
    listDiv.waterMarkList.push(watermark);
}

function toggleClass() {
    var node = this.nextElementSibling;
    var reg = new RegExp("(\\s|^)hidden(\\s|$)");
    while (node && node.className.indexOf("row title") === -1 && node.className.indexOf("btn-set") === -1) {
        if (node.className.match(reg)) {
            node.className = node.className.replace(reg, "");
        } else {
            node.className += " hidden";
        }
        node = node.nextElementSibling;
    }
}

function adjustLayoutForPrint(sheet) {
    // 添加两列，设置序号；添加两行空白行
    // sheet.addColumns(0, 2);
    // sheet.setColumnWidth(0, 30);
    // sheet.setColumnWidth(1, 30);
    // for (var r = 5; r <= 200; r += 5) {
    //     sheet
    //         .getCell(r, 1)
    //         .text(r + "")
    //         .font("normal 9px Arial");
    // }
    // sheet.addRows(0, 2);
    // sheet.setRowHeight(0, 10);
    // sheet.setRowHeight(1, 10);
}
